package com.hbisedm.interninfosys.intern.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbisedm.interninfosys.commonutils.R;
import com.hbisedm.interninfosys.intern.entity.*;
import com.hbisedm.interninfosys.intern.entity.queryVo.UserQuery;
import com.hbisedm.interninfosys.intern.service.*;
import com.hbisedm.interninfosys.intern.service.impl.MenuServiceImpl;
import com.hbisedm.interninfosys.utils.AliyunOssUtil;
import com.hbisedm.interninfosys.utils.MenuChangeUtil;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sam
 * @since 2020-12-04
 */
@RestController
@RequestMapping("/intern/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IInternshipInfoService internshipInfoService;

    @Autowired
    private IRoleMenuService roleMenuService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private MenuServiceImpl menuService;

    @Autowired
    private IStuInternshipService stuInternshipService;

    @Value("${pathUrl}")
    private String pathUrl;

    @Autowired
    private IStuTeachService stuTeachService;

    /**
     * 用户信息接口
     * 登录后调用
     * @return
     */
    @GetMapping("/info")
    public R info() {
        /**
         * todo 获取角色信息，以及对应的菜单信息
         */
        List<String> currentRole = MenuChangeUtil.getCurrentRole();
        //默认第一个
        String roleName = currentRole.get(0);
        String root = "管理员";
        List<Menu> menuList = null;
        Map<String, Object> relation = new HashMap<>();
        /**
         * 通过id 辨别是学生，老师，企业
         */
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User one = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        Integer type = new Integer(0);
        Integer oneType = one.getType();
        /**
         * todo 不用转， 直接发0， 1， 2， 3 给前台， 前台判断处理就行
         */
        switch (oneType) {
            case 0:
                type = 0;
                break;
            case 1:
                type = 1;
                StuInternship stuInternship = stuInternshipService.getBaseMapper().selectOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, one.getId()));
                StuTeach stuTeach = stuTeachService.getBaseMapper().selectOne(new QueryWrapper<StuTeach>().lambda().eq(StuTeach::getSid, one.getId()));
                relation.put("sid", one.getId());
                if(stuTeach!=null) {
                    Optional<Integer> tid = Optional.ofNullable(stuTeach.getTid());
                    if (tid.isPresent()) {
                        relation.put("tid", stuTeach.getTid());
                    }
                }
                Optional<StuInternship> stuInternship1 = Optional.ofNullable(stuInternship);
                if(stuInternship1.isPresent()) {
                    Optional<Integer> iid = Optional.ofNullable(stuInternship.getIid());
                    if(iid.isPresent()) {
                        relation.put("iid", stuInternship.getIid());
                    }
                }
                break;
            case 2:
                type = 2;
                List<StuTeach> stuTeaches = stuTeachService.getBaseMapper().selectList(new QueryWrapper<StuTeach>().lambda().eq(StuTeach::getTid, one.getId()));
                ArrayList<Integer> sids = new ArrayList<>();
                for (StuTeach teach : stuTeaches) {
                    sids.add(teach.getSid());
                }
                relation.put("sids", sids);
                relation.put("tid", one.getId());
                break;
            case 3:
                type = 3;
                List<StuInternship> stuInternships = stuInternshipService.getBaseMapper().selectList(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getIid, one.getId()));
                ArrayList<Integer> sidss = new ArrayList<>();
                for (StuInternship internship : stuInternships) {
                    sidss.add(internship.getSid());
                }
                relation.put("iid", one.getId());
                relation.put("sids", sidss);
                break;
            default:
                type = 404; //无效身份
        }

        InternshipInfo internshipInfo = null;
        if(oneType == 3) {
            internshipInfo = internshipInfoService.getOne(new QueryWrapper<InternshipInfo>().lambda().eq(InternshipInfo::getUid, one.getId()));

        }

        /**
         * 给对应角色 对应的菜单
         */
        if (root.equals(roleName)){
            menuList = menuService.list();
        }else {
            /**
             * todo 获取role_menus表对应的menus
             * okk
             */
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("ROLE_NAME", roleName);
            Role role = roleService.getBaseMapper().selectOne(roleQueryWrapper);
            QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
            roleMenuQueryWrapper.eq("ROLE_ID", role.getId());
            List<RoleMenu> roleMenus = roleMenuService.getBaseMapper().selectList(roleMenuQueryWrapper);
            List<Integer> idList = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
            QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
            menuQueryWrapper.in("MENU_ID", idList);
            menuList = menuService.getBaseMapper().selectList(menuQueryWrapper);
        }
        List<LastMenu> lastMenus = menuService.initMenu(menuList);

//        System.out.println(JSON.toJSONString(lastMenus));

        return R.ok()
                .data("type", type)
                .data("relation", relation)
                .data("name", MenuChangeUtil.getCurrentName())
                .data("companyName", MenuChangeUtil.getCurrentName())
                .data("obj", one)
                .data("menus", lastMenus)
                .data("roles", currentRole)
                .data("internshipInfo", internshipInfo)
                .data("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
    }

    /**
     * 注册接口
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R registerUser(@RequestBody User user){
        /**
         * todo 获取user表信息，通过username
         * todo 每个username唯一，注册重复报警告
         */
        System.out.println(user);
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userService.save(user);
        Integer id = user.getId();
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        /**
         * 设置成普通用户 setRoleId（2）
         */
        userRole.setRoleId(2);
        boolean save = userRoleService.save(userRole);
        if(save) {
            return R.ok();
        }
        return R.error();
    }


    @PostMapping("/list/{current}/{limit}")
    public R list(@PathVariable long current,
                  @PathVariable long limit,
                  @RequestBody(required = false) UserQuery userQuery) {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        String name = userQuery.getName();
        String begin = userQuery.getBegin();
        String end = userQuery.getEnd();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(name)){
            userQueryWrapper.like("OTHERNAME", name);
        }
        if(!StringUtils.isEmpty(begin)){
            userQueryWrapper.ge("CREATE_TIME", begin);
        }
        if(!StringUtils.isEmpty(end)){
            userQueryWrapper.le("CREATE_TIME", end);
        }

//        userQueryWrapper.orderByDesc("CREATE_TIME");

        Page<User> userPage = new Page<>(current, limit);
        userService.page(userPage,userQueryWrapper);
        /**
         * 总记录数
         */
        long total = userPage.getTotal();
        List<User> userList = userPage.getRecords();
        System.out.println(userList);
        return R.ok()
                .data("total",total)
                .data("items", userList);
    }


    @DeleteMapping("/delete/{id}")
    public R removeUser(@ApiParam(name = "id", value = "讲师ID", required = true)
                            @PathVariable Integer id) {
        boolean b = userService.removeById(id);
        if(b){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @PostMapping("/updateUser")
    public R updateUser(@RequestBody User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        boolean b = userService.updateById(user);
        if(b){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @GetMapping("/getUser/{id}")
    public R getUser(@PathVariable Integer id) {
        User user = userService.getById(id);
        return R.ok().data("user", user);
    }


    @Autowired
    private AliyunOssUtil ossUtil;


    /**
     * 改变头像
     * @param file
     * @return
     */
    @PostMapping("/changeAvatar/{id}")
    @ResponseBody
    public String changeAvatar(@RequestParam("file") MultipartFile file, @PathVariable("id") Integer id) {
        try {
            User currentUser = userService.getById(id);
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);

                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();

                    //把file里的内容复制到newFile中
                    file.transferTo(newFile);

                    String upload = ossUtil.upload(newFile);

                    System.out.println("path=" + upload);
                    String url = pathUrl + upload;
                    currentUser.setAvatar(url);
                    userService.updateById(currentUser);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";
    }

    /**
     * 企业或者教师 修改 印章或者电子签名
     * @param file
     * @param id
     * @return
     */
    @PostMapping("/changeSignature/{id}")
    @ResponseBody
    public String changeSignature(@RequestParam("file") MultipartFile file, @PathVariable("id") Integer id) {
        try {
            User currentUser = userService.getById(id);
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);

                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();

                    //把file里的内容复制到newFile中
                    file.transferTo(newFile);

                    String upload = ossUtil.upload(newFile);

                    System.out.println("path=" + upload);
                    String url = pathUrl + upload;
                    currentUser.setSignature(url);
                    userService.updateById(currentUser);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";
    }

}
